import nunjucks from 'nunjucks';
import path from 'path';
import fs from 'fs';
import log from 'fancy-log';
import chalk from 'chalk';

import { ConfigureOptions } from './types';
import { DEFAULT_CONFIG_OPTIONS } from './constansts';
import { convertSVGToTSXAsync, convertToSVGFileModel, getSVGFiles } from './utils';

function configure() {
    nunjucks.configure({ autoescape: false });
}

export default function (config: ConfigureOptions) {
    const template = config?.template || (DEFAULT_CONFIG_OPTIONS.template as string);
    const templatePath = path.isAbsolute(template) ? template : path.join(process.cwd(), template);
    const templateContent = fs.readFileSync(templatePath)?.toString();

    const svgDir = path.isAbsolute(config?.targetPath)
        ? config?.targetPath
        : path.join(process.cwd(), config.targetPath);

    log(chalk.green('Looking for SVG Icons in:', svgDir));
    log(chalk.green('Using Icon template from:', templatePath));

    const svgPaths = getSVGFiles(svgDir);

    log(chalk.green(`Find ${svgPaths?.length ?? 0} Icon(s) need to convert`));

    configure();

    const convertSVGFilePromises = svgPaths.map((path) =>
        convertSVGToTSXAsync(templateContent, path, config?.outputPath),
    );

    return Promise.all(convertSVGFilePromises)
        .then((result) => {
            log(chalk.bgGreen('Congratulations, all Icon convert is done!'));
        })
        .catch((err) => {
            log(chalk.green('Convert SVG To TSX Error:', err));
        });
}
